3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
20 use Psr\Log\LoggerInterface
;
21 use Psr\Log\LoggerAwareInterface
;
24 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
26 * This class simply wraps the Redis class and can be used the same way
31 class RedisConnRef
implements LoggerAwareInterface
{
32 /** @var RedisConnectionPool */
37 protected $server; // string
38 protected $lastError; // string
41 * @var LoggerInterface
46 * No authentication errors.
50 const AUTH_NO_ERROR
= 200;
53 * Temporary authentication error; recovered by reauthenticating.
57 const AUTH_ERROR_TEMPORARY
= 201;
60 * Authentication error was permanent and could not be recovered.
64 const AUTH_ERROR_PERMANENT
= 202;
67 * @param RedisConnectionPool $pool
68 * @param string $server
70 * @param LoggerInterface $logger
72 public function __construct(
73 RedisConnectionPool
$pool, $server, Redis
$conn, LoggerInterface
$logger
76 $this->server
= $server;
78 $this->logger
= $logger;
81 public function setLogger( LoggerInterface
$logger ) {
82 $this->logger
= $logger;
89 public function getServer() {
93 public function getLastError() {
94 return $this->lastError
;
97 public function clearLastError() {
98 $this->lastError
= null;
102 * Magic __call handler for most Redis functions.
104 * @param string $name
105 * @param array $arguments
107 * @throws RedisException
109 public function __call( $name, $arguments ) {
110 // Work around https://github.com/nicolasff/phpredis/issues/70
111 $lname = strtolower( $name );
113 ( $lname === 'blpop' ||
$lname === 'brpop' ||
$lname === 'brpoplpush' )
114 && count( $arguments ) > 1
116 // Get timeout off the end since it is always required and argument length can vary
117 $timeout = end( $arguments );
118 // Only give the additional one second buffer if not requesting an infinite timeout
119 $this->pool
->resetTimeout( $this->conn
, ( $timeout > 0 ?
$timeout +
1 : $timeout ) );
122 return $this->tryCall( $name, $arguments );
126 * Do the method call in the common try catch handler.
128 * @param string $method
129 * @param array $arguments
131 * @throws RedisException
133 private function tryCall( $method, $arguments ) {
134 $this->conn
->clearLastError();
136 $res = $this->conn
->$method( ...$arguments );
137 $authError = $this->checkAuthentication();
138 if ( $authError === self
::AUTH_ERROR_TEMPORARY
) {
139 $res = $this->conn
->$method( ...$arguments );
141 if ( $authError === self
::AUTH_ERROR_PERMANENT
) {
142 throw new RedisException( "Failure reauthenticating to Redis." );
145 $this->postCallCleanup();
153 * Handle this explicity due to needing the iterator passed by reference.
154 * See: https://github.com/phpredis/phpredis#scan
156 * @param int &$iterator
157 * @param string|null $pattern
158 * @param int|null $count
161 public function scan( &$iterator, $pattern = null, $count = null ) {
162 return $this->tryCall( 'scan', [ &$iterator, $pattern, $count ] );
167 * Handle this explicity due to needing the iterator passed by reference.
168 * See: https://github.com/phpredis/phpredis#sScan
171 * @param int &$iterator
172 * @param string|null $pattern
173 * @param int|null $count
176 public function sScan( $key, &$iterator, $pattern = null, $count = null ) {
177 return $this->tryCall( 'sScan', [ $key, &$iterator, $pattern, $count ] );
182 * Handle this explicity due to needing the iterator passed by reference.
183 * See: https://github.com/phpredis/phpredis#hScan
186 * @param int &$iterator
187 * @param string|null $pattern
188 * @param int|null $count
191 public function hScan( $key, &$iterator, $pattern = null, $count = null ) {
192 return $this->tryCall( 'hScan', [ $key, &$iterator, $pattern, $count ] );
197 * Handle this explicity due to needing the iterator passed by reference.
198 * See: https://github.com/phpredis/phpredis#hScan
201 * @param int &$iterator
202 * @param string|null $pattern
203 * @param int|null $count
206 public function zScan( $key, &$iterator, $pattern = null, $count = null ) {
207 return $this->tryCall( 'zScan', [ $key, &$iterator, $pattern, $count ] );
211 * Handle authentication errors and automatically reauthenticate.
213 * @return constant self::AUTH_NO_ERROR, self::AUTH_ERROR_TEMPORARY, or self::AUTH_ERROR_PERMANENT
215 private function checkAuthentication() {
216 if ( preg_match( '/^ERR operation not permitted\b/', $this->conn
->getLastError() ) ) {
217 if ( !$this->pool
->reauthenticateConnection( $this->server
, $this->conn
) ) {
218 return self
::AUTH_ERROR_PERMANENT
;
220 $this->conn
->clearLastError();
222 "Used automatic re-authentication for Redis.",
223 [ 'redis_server' => $this->server
]
225 return self
::AUTH_ERROR_TEMPORARY
;
227 return self
::AUTH_NO_ERROR
;
231 * Post Redis call cleanup.
235 private function postCallCleanup() {
236 $this->lastError
= $this->conn
->getLastError() ?
: $this->lastError
;
238 // Restore original timeout in the case of blocking calls.
239 $this->pool
->resetTimeout( $this->conn
);
243 * @param string $script
244 * @param array $params
245 * @param int $numKeys
247 * @throws RedisException
249 public function luaEval( $script, array $params, $numKeys ) {
250 $sha1 = sha1( $script ); // 40 char hex
251 $conn = $this->conn
; // convenience
252 $server = $this->server
; // convenience
254 // Try to run the server-side cached copy of the script
255 $conn->clearLastError();
256 $res = $conn->evalSha( $sha1, $params, $numKeys );
257 // If we got a permission error reply that means that (a) we are not in
258 // multi()/pipeline() and (b) some connection problem likely occurred. If
259 // the password the client gave was just wrong, an exception should have
260 // been thrown back in getConnection() previously.
261 if ( preg_match( '/^ERR operation not permitted\b/', $conn->getLastError() ) ) {
262 $this->pool
->reauthenticateConnection( $server, $conn );
263 $conn->clearLastError();
264 $res = $conn->eval( $script, $params, $numKeys );
266 "Used automatic re-authentication for Lua script '$sha1'.",
267 [ 'redis_server' => $server ]
270 // If the script is not in cache, use eval() to retry and cache it
271 if ( preg_match( '/^NOSCRIPT/', $conn->getLastError() ) ) {
272 $conn->clearLastError();
273 $res = $conn->eval( $script, $params, $numKeys );
275 "Used eval() for Lua script '$sha1'.",
276 [ 'redis_server' => $server ]
280 if ( $conn->getLastError() ) { // script bug?
281 $this->logger
->error(
282 'Lua script error on server "{redis_server}": {lua_error}',
284 'redis_server' => $server,
285 'lua_error' => $conn->getLastError()
290 $this->lastError
= $conn->getLastError() ?
: $this->lastError
;
299 public function isConnIdentical( Redis
$conn ) {
300 return $this->conn
=== $conn;
303 function __destruct() {
304 $this->pool
->freeConnection( $this->server
, $this->conn
);